// 引入 Dialog

import Dialog from '@vant/weapp/dialog/dialog';

import { checkMaterial, saveCheck, saveDetail } from "@/api/check.js"
Page({
  data: {
    activeNames: [],
    checked: true,
    checkGroups: {},
    saveData:[],
    isEmpty: true,
    groupedByLocation: {},
    show: false,

  },
  // const warehouseName = dataset.location; // 所在位置
  // const categoryName = dataset.category; // 类别名称
  // const assetIndex = dataset.index; // 类别名称
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
    console.log("onChange", this.data.activeNames)
  },
 
  handleUpNum(e){
    
  console.log(e.currentTarget.dataset.id,e,this.data.checkGroups);
   // 遍历每个 location
   let saveData=[];
   let materialId=e.currentTarget.dataset.id;
   let inventoryid=e.currentTarget.dataset.inventoryid;
   const groupedByLocation = this.data.checkGroups;
   for (let location in groupedByLocation) {
    const categories = groupedByLocation[location];
    // 遍历每个分类（如电脑、手机）
    for (let warehouseName in categories) {
      const assets = categories[warehouseName];
     if(assets.materialId==materialId && assets.inventoryId==inventoryid){
       assets.actualQuantity=e.detail
     }
     saveData .push(assets)
    }
  }
  this.setData({
    saveData
  })
  },
  async onSaveCheck() {
   if(this.data.saveData.length==0){
     wx.showToast({
       title: '请盘点数据',
       icon:"error",
       mask:true
     })
     return;
   }
        //处理数据
    console.log(this.data.saveData)
    // 更新数据
    wx.showLoading({
      title: '正在提交中',
      mask:true
    })
    const resule=await saveCheck(this.data.saveData)
    if(resule.code==200){
      wx.showToast({
        title: '提交成功',
        mask:true,
        icon:"success",
        duration:1500,
        complete(){
          setTimeout(()=>{
            wx.navigateBack()
          },1500)
        }
      })
      wx.hideLoading()
      
    }else{
      wx.showToast({
        title: '提交失败',
        mask:true
      })
      wx.hideLoading()
    }
  },
  groupByLocationAndCategory(data) {
    const groupedByLocation = {};

    data.forEach(item => {
      const { warehouseName, name } = item;
  
      if (!groupedByLocation[warehouseName]) {
        groupedByLocation[warehouseName] = {};
      }
  
      if (!groupedByLocation[warehouseName][name]) {
        groupedByLocation[warehouseName][name] = item;
      }
    });
    return groupedByLocation;
  },
  async getCheckList(id) {
    console.log(id)
    this.setData({
      checkGroups: []
    });
    const result=await checkMaterial(id)
    console.log("checkMaterial", result);
    var group = this.groupByLocationAndCategory(result.data);
    this.setData({
      checkGroups: group,
      isEmpty: Object.keys(group).length === 0
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onLoad(options) {
    console.log(options);
    this.getCheckList(options.id);
  },

});